package com.zx.cloud.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Downloader {

	private int threadNum;
	private int contentLength;
	private String targetFileName;
	private String url;
	private int[] downloadThreads;

	public Downloader(String url, int threadNum, String targetFileName) {
		this.url = url;
		this.threadNum = threadNum;
		this.targetFileName = targetFileName;
		downloadThreads = new int[threadNum];
	}

	public void download() throws Exception {
		URL url2 = new URL(url);
		HttpURLConnection httpURLConnection = (HttpURLConnection) url2.openConnection();
		contentLength = httpURLConnection.getContentLength();
		int partSize = contentLength / threadNum + 1;
		RandomAccessFile randomAccessFile = new RandomAccessFile(targetFileName, "rw");
		randomAccessFile.setLength(contentLength);
		randomAccessFile.close();
		httpURLConnection.disconnect();
		if ("bytes".equals(httpURLConnection.getHeaderField("Accept-Ranges"))) {
			for (int i = 0; i < threadNum; i++) {
				int startPos = i * partSize;
				RandomAccessFile randomAccessWriter = new RandomAccessFile(targetFileName, "rw");
				randomAccessWriter.seek(startPos);
				new Thread(buildRunnable(url, startPos, partSize, randomAccessWriter)).start();
			}
		} else {
			new Thread(buildRunnable(url, 0, partSize, new RandomAccessFile(targetFileName, "rw"))).start();
		}
	}

	private Runnable buildRunnable(final String path, final int startPos, final int partSize, final RandomAccessFile randomAccessFile) {
		return new Runnable() {
			@Override
			public void run() {
				try {
					URL url = new URL(path);
					HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
					InputStream inputStream = httpURLConnection.getInputStream();
					inputStream.skip(startPos);
					int b;
					int length = 0;
					while (length < partSize && (b = inputStream.read()) != -1) {
						length++;
						randomAccessFile.write(b);
					}
					randomAccessFile.close();
					httpURLConnection.disconnect();
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		};
	}

	public double getComplete() {
		double sum = 0;
		for (int i = 0; i < threadNum; i++) {
			sum += downloadThreads[i];
		}
		return sum * 1.0 / contentLength;
	}
}